import logging
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from dbmodel import Competition
from dbmodel import Class
from dbmodel import TimeFunctions
from google.appengine.api import quota
from google.appengine.api import memcache
import os
from datetime import datetime
from datetime import timedelta
from displayresultrow import displayresultrow

class PlainRenderer():

	def renderResultList(self, key, comp_class):
	    comp = memcache.get(key)
	    if comp is None:
	    	comp = db.get(key)
		memcache.set(key,comp,3600)

	    classes = memcache.get(key + "_classes")
	    if classes is None:    	
	    	q = db.GqlQuery('SELECT * from Class where competitionid = :1 order by name',comp.key())
	    	classes = q.fetch(100)
	    	memcache.set(key+"_classes",classes,3600)

	    curradios = []
	    curclassident = None
	    classresults = None
	    

	    if comp_class != None and comp_class != '':
   		
		cl = memcache.get(key + "_class_" + comp_class)
		if cl == None:
		  	q = db.GqlQuery('SELECT * from Class WHERE competitionid = :1 and name = :2',comp.key(),comp_class)
    			cl = q.get()
			memcache.set(key + "_class_" + comp_class, cl, 3600)

		if cl == None:
			return
		curclassident = cl.ident
		for item in cl.ControlNames:
			curradios.append(item)
		    
	    	q = db.GqlQuery('SELECT * from Runner where runnerClass = :1 order by status, totaltime',cl.key())
	    	cr = q.fetch(100)
	    	plac = 0
	    	lasttime = -9999
	    	firsttime = 0
	    	classresults = []
	    	tf = TimeFunctions()

	    	for item in cr:
				if item.totaltime != lasttime:
					plac = plac+1
				if firsttime == 0:
					firsttime = item.totaltime

				sTimes = []
				for code in cl.ControlCodes:
					if item.SplitControls != None:
						if code in item.SplitControls and item.SplitTimes[item.SplitControls.index(code)] > 0:
							sTimes.append(tf.formatTime(item.SplitTimes[item.SplitControls.index(code)],0))
						else:
							sTimes.append('-')
					else:
						sTimes.append('-')

				
				classresults.append(displayresultrow(plac = plac if item.status == 0 else '', name = item.firstname + " " + item.lastname, clubname = item.clubname, time = tf.formatTime(item.totaltime,item.status), timeplus =  ('+' + tf.formatTime(item.totaltime-firsttime, 0)) if item.status == 0 else '', status= 'updated' if item.changetime <> None and (datetime.now() - item.changetime).seconds < 3*60 else '', splits = sTimes ))
				lasttime = item.totaltime
	    if classresults != None:
		    classresults = sorted(classresults)	

	    template_values = {
		'comp' : comp,
		'classes' : classes,
		'curclass' : comp_class,
		'curradios' : curradios,
		'curclassident' : curclassident,
		'classresults' : classresults,
		'usage' :    quota.get_request_cpu_usage(),
		'rendertime' : datetime.now()
		}

	    path = os.path.join(os.path.dirname(__file__), 'result_with_splits.html')
	    data = template.render(path, template_values)
	    if comp_class != None:
	   	memcache.set('results_'+key+'_'+comp_class,data,60)
		memcache.set(key + "_" + comp_class +"_lastrender",datetime.now(),15)


	    return data
